
#include "softmax_tiling.h"
#include "register/op_def_registry.h"
#include "tiling/platform/platform_ascendc.h"


namespace optiling {
    const uint32_t BLOCK_SIZE = 32;
static ge::graphStatus TilingFunc(gert::TilingContext* context)
{

    SoftmaxTilingData tiling;
    constexpr int32_t NUM = 5;
    const gert::StorageShape* x1_shape = context->GetInputShape(0);
    uint32_t sizeofdatatype;
    uint32_t totallengthAligned;
    auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo());
    auto socVersion = ascendcPlatform.GetSocVersion();
    uint64_t ub_size;
    ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub_size);
    uint32_t totallength = context->GetInputShape(0)->GetStorageShape().GetShapeSize();
    auto dt = context->GetInputDesc(0)->GetDataType();
    if(dt == ge::DT_INT8){
        sizeofdatatype = 1;
    }else if(dt == ge::DT_FLOAT16 || dt == ge::DT_BF16){
        sizeofdatatype = 2;
    }
    else if (dt == ge::DT_INT32) {
        sizeofdatatype = 4;
    }
    else{
        sizeofdatatype = 4;
    }

    uint32_t ALIGN_NUM = BLOCK_SIZE / sizeofdatatype;
    uint32_t tiling_size = ((ub_size) / BLOCK_SIZE / 2) / NUM;
    tiling_size = tiling_size <= 8 ? tiling_size : tiling_size / 8 * 8;
    uint32_t tilelength = tiling_size * ALIGN_NUM;
    tiling.set_tilelength(tilelength);

    int32_t dimnum = context->GetInputShape(0)->GetStorageShape().GetDimNum();
    int32_t lastdimnum = context->GetInputShape(0)->GetStorageShape().GetDim(dimnum - 1);
    tiling.set_lastdimnum(lastdimnum);

    auto ptr = context->GetAttrs()->GetInt(0);
    tiling.set_dim(*ptr);
    
    int32_t loopcount = totallength / lastdimnum;
    tiling.set_loopcount(loopcount);
    tiling.set_totallength(totallength);

    if(*ptr == -1 || *ptr == (dimnum - 1)) {
        if(lastdimnum <= tilelength) {
            context->SetTilingKey(1);
        } else {
            context->SetTilingKey(2);    //for long dim 
        }
    } else {
        if(lastdimnum <= tilelength) {
            context->SetTilingKey(3);     
        } else {
            context->SetTilingKey(4);    //for long dim 
        }
    }
    int32_t dim = (*ptr < 0) ? dimnum + *ptr : *ptr;    
    auto tiling_key = context->GetTilingKey();
    int32_t v1stlevelloop = 0;
    int32_t v2ndlevleloop = 0;
    int32_t v1stlevelgap = 0;
    int32_t v2ndlevelgap = 0;
    int32_t v3rdlevleloop = 0;
    if(tiling_key == 3 || tiling_key == 4) {
        v1stlevelloop = 1;
        for(int32_t k = 0; k < dim; k++) {
            v1stlevelloop *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
        }
        v2ndlevleloop = context->GetInputShape(0)->GetStorageShape().GetDim(dim);
        v1stlevelgap = totallength / v1stlevelloop;
        v2ndlevelgap = 1;
        for(int32_t k = dim + 1; k < dimnum; k++) {
            v2ndlevelgap *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
        }
        v3rdlevleloop = 1;
        for(int32_t k = dim + 1; k < dimnum - 1; k++) {
            v3rdlevleloop *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
        }
    }
    // optimization 
    if(tiling_key == 3 || tiling_key == 4) {
        for(int32_t k = dimnum - 2; k > dim; k--) {
            if(lastdimnum * context->GetInputShape(0)->GetStorageShape().GetDim(k) < tilelength) {
                lastdimnum *= context->GetInputShape(0)->GetStorageShape().GetDim(k);
                v3rdlevleloop = v3rdlevleloop / context->GetInputShape(0)->GetStorageShape().GetDim(k);
                tiling.set_lastdimnum(lastdimnum);
            }
        }    
    }
    //special case for dimsize = 1
    int32_t  dimsize = context->GetInputShape(0)->GetStorageShape().GetDim(dim);
    if(dimsize == 1) {
        context->SetTilingKey(5);
    }
    //specail case for lastdimnum is aligned
    int32_t connectnum = 1;
    if(tiling_key == 1) {
        if(lastdimnum % ALIGN_NUM == 0) {
            connectnum = tilelength / lastdimnum;
            if(connectnum > 1) {
                context->SetTilingKey(6);
                tiling.set_connectnum(connectnum);
            }
        }
    }  
    std::vector<int64_t> shapeVec = {connectnum, lastdimnum};
    ge::Shape srcShape(shapeVec);
    const uint32_t localWorkSpaceSize = AscendC::GetSoftMaxMinTmpSize(srcShape, sizeofdatatype, false);
    // 获取SoftMax Tiling参数
    AscendC::SoftMaxTilingFunc(srcShape, sizeofdatatype, localWorkSpaceSize, tiling.softmaxTilingData);       

    tiling.set_v1stlevelloop(v1stlevelloop);
    tiling.set_v2ndlevleloop(v2ndlevleloop);
    tiling.set_v1stlevelgap(v1stlevelgap);
    tiling.set_v2ndlevelgap(v2ndlevelgap);
    tiling.set_v3rdlevleloop(v3rdlevleloop);
    std::cout << "tiling_key:" << context->GetTilingKey() << std::endl;
    std::cout << "ALIGN_NUM:" << ALIGN_NUM << std::endl;
    std::cout << "dimnum:" << dimnum << std::endl;
    std::cout << "totallength:" << totallength << std::endl;
    std::cout << "tilelength:" << tilelength << std::endl;
    std::cout << "dim_ptr:" << *ptr << std::endl;
    std::cout << "dim:" << dim << std::endl;
    std::cout << "lastdimnum:" << lastdimnum << std::endl;
    std::cout << "loopcount:" << loopcount << std::endl;
    std::cout << "v1stlevelloop:" << v1stlevelloop << std::endl;
    std::cout << "v2ndlevleloop:" << v2ndlevleloop << std::endl;
    std::cout << "v1stlevelgap:" << v1stlevelgap << std::endl;
    std::cout << "v2ndlevelgap:" << v2ndlevelgap << std::endl;
    std::cout << "v3rdlevleloop:" << v3rdlevleloop << std::endl;
    std::cout << "connectnum:" << connectnum << std::endl;

    context->SetBlockDim(1);
    tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity());
    context->GetRawTilingData()->SetDataSize(tiling.GetDataSize());

    return ge::GRAPH_SUCCESS;
}
}


namespace ge {
static ge::graphStatus InferShape(gert::InferShapeContext* context)
{
    const gert::Shape* x1_shape = context->GetInputShape(0);
    gert::Shape* y_shape = context->GetOutputShape(0);
    *y_shape = *x1_shape;
    return GRAPH_SUCCESS;
}
}


namespace ops {
class Softmax : public OpDef {
public:
    explicit Softmax(const char* name) : OpDef(name)
    {
        this->Input("x")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Output("y")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Attr("dim").AttrType(OPTIONAL).Int(-1);

        this->SetInferShape(ge::InferShape);

        this->AICore()
            .SetTiling(optiling::TilingFunc);
        this->AICore().AddConfig("ascend310b");

    }
};

OP_ADD(Softmax);
}
